package com.yjzx.util.common.util.BeanUtils;

import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author yjzx
 * @date 2024/8/14
 * @description LambdaField
 */
public interface LambdaFieldGetter extends LambdaField {
    @Override
    default Method getColumnSetterMethod() {
        try {
            Class<?> aClass = this.getClassFromLambda();
            Field field = this.getLambdaColumn();
            if (field != null) {
                String methodName = PREFIX_SETTER + field.getName();
                return aClass.getMethod(methodName, field.getType());
            }
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        return null;
    }

    @Override
    default Method getColumnGetterMethod() {
        return getMethodFromLambda();
    }

    /**
     * 获取getter方法的属性对象
     *
     * @return
     */
    @Override
    default Field getLambdaColumn() {
        try {
            SerializedLambda serializedLambda = getSerializedLambda();
            // 获取方法名称
            String getter = serializedLambda.getImplMethodName();
            Class<?> declaringClass = getClassByClassName(serializedLambda.getImplClass());
            String name = null;
            if (getter != null) {
                if (getter.startsWith(PREFIX_GETTER_GETTER)) {
                    name = getter.replace(PREFIX_GETTER_GETTER, "");

                } else if (getter.startsWith(PREFIX_GETTER_IS)) {
                    name = getter.replace(PREFIX_GETTER_IS, "");
                }
            }
            return getField(declaringClass, name);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

}
